package com.fjec.common.wx;

import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.exception.WechatException;
import com.fjec.common.okhttp.OkHttp;
import com.fjec.common.util.JsonUtil;
import com.google.common.base.Strings;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Data
public class WxAccessTokenHelper {

    public final static String REDIS_ACCECCTOKEN_KEY = "fjec_wx_access_token";

    private OkHttp okHttp;

    private WxProperties properties;

    private RedisTemplate redisTemplate;

    public WxAccessTokenHelper(OkHttp okHttp, WxProperties properties) {
        this.okHttp = okHttp;
        this.properties = properties;
    }

    public String getAccessTokenEx() {
        Object obj = redisTemplate.opsForValue().get(REDIS_ACCECCTOKEN_KEY);
        return obj == null ? "" : obj.toString();
    }

    /**
     * 获取access_token
     * 文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
     *
     * @return
     */
    @Cacheable(cacheNames = "c_120", key = "'fjec_wx_access_token'")
    public String getAccessToken() {
        return doGetAccessToken();
    }

    @CachePut(cacheNames = "c_120", key = "'fjec_wx_access_token'")
    public String cacheAccessToken() {
        return doGetAccessToken();
    }

    @CacheEvict(cacheNames = "c_120", key = "'fjec_wx_access_token'")
    public void removeAccessToken() {
        log.info("Remove wx access token.");
    }

    public String doGetAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, String> inParameters = new HashMap<>();
        inParameters.put("grant_type", "client_credential");
        inParameters.put("appid", properties.getAppId());
        inParameters.put("secret", properties.getAppSecret());
        //调用微信接口
        String result = okHttp.postMap(url, inParameters);
        if (log.isDebugEnabled()) {
            log.debug("请求微信AccessToken 返回结果=" + result);
        }
        Map<String, Object> map = JsonUtil.jsonToMap(result);
        System.out.println("当前数据" + map);
        //判断返回结果是否错误
        if (map.containsKey("errcode")) {
            throw new WechatException(EnumSysCode.ERR_0011, MapUtils.getString(map, "errcode"),
                    MapUtils.getString(map, "errmsg"));
        }
        return map.get("access_token").toString();
    }

    /**
     * 获取我们微信缓存中心的AccessToken
     *
     * @return
     */
    public String getWxCenterAccessToken() {
        String url = properties.getWxCenterUrl() + "/api/get/access/token";
        String accessToken = okHttp.get(url);
        if (!Strings.isNullOrEmpty(accessToken)) {
            return accessToken;
        } else {
            return null;
        }
    }

    /**
     * 刷新我们微信缓存中心的AccessToken
     *
     * @return
     */
    public String refreshWxCenterAccessToken() {
        String url = properties.getWxCenterUrl() + "/api/refresh/access/token";
        String accessToken = okHttp.get(url);
        if (!Strings.isNullOrEmpty(accessToken)) {
            return accessToken;
        } else {
            return null;
        }
    }
}
